package xjtu.se.articlecommunity.user.register;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import xjtu.se.articlecommunity.common.*;
import xjtu.se.articlecommunity.user.register.dao.UserMapper;
import xjtu.se.articlecommunity.user.register.dto.RegisterDto;

import javax.annotation.Resource;

@Slf4j
@RestController
@RequestMapping("/user/register")
public class RegisterAPI {
    @Resource
    UserMapper userMapper;

    @Resource
    MailService mailService;
    @Resource
    SMSService smsService;

    @Resource
    CacheService cacheService;



    @GetMapping("/mailcode")
    public Result mailcode(@RequestParam("mail") String mail) {
        log.info(mail);
        if (userMapper.ifUserExist(mail) > 0) {
            return Result.fail(500, "该邮箱已经注册");
        }
        String mailcode = mailService.sendCode(mail);
        log.info(mailcode);
        cacheService.saveVerificationCode(mail, mailcode);
        return Result.success();
    }

    @GetMapping("/telcode")
    public Result telcode(@RequestParam("tel") String tel) {
        log.info(tel);
        if (userMapper.ifUserExist(tel) > 0) {
            return Result.fail(500, "该手机号已经注册");
        }
        String telcode = smsService.sendVerificationCode(tel);
        log.info(telcode);
        cacheService.saveVerificationCode(tel, telcode);
        return Result.success();
    }



    @PostMapping("/addUser")
    public Result addUser(@RequestBody RegisterDto register) {
        log.info(register.toString());
        if(cacheService.findVerificationCode(register.getMail()).equals(register.getMailcode())){
            String uid=Uid.uid();
            userMapper.addUser(uid,register.getMail(),register.getPassword());
            String token = TokenUtils.loginSign(uid,register.getPassword(),0);
            return Result.success((Object)token);
        }
        return Result.fail(500,"验证码失效或错误");
    }
    @PostMapping("/addUser2")
    public Result addUser2(@RequestBody RegisterDto register) {
        log.info(register.toString());
        if(cacheService.findVerificationCode(register.getMail()).equals(register.getMailcode())){
            String uid=Uid.uid();
            userMapper.addUser(uid,register.getMail(),register.getPassword());
            String token = TokenUtils.loginSign(uid,register.getPassword(),0);
            return Result.success((Object)token);
        }
        return Result.fail(500,"验证码失效或错误");
    }
}
